import webbrowser
import requests
import datetime
import time
import os

# tomcat的启动路径
# tomcatStart = "D:\\kaiFa\\tomcat 8.0.2.9_20151204\\apache-tomcat-8.0.29-64\\bin\\startup.bat"
# tomcatStart = "E:\\chinaweal\\apache-tomcat-7.0.47\\bin\\startup.bat"  旧的
tomcatStart = "E:\\chinaweal\\apache-tomcat-7.0.85\\bin\\startup.bat"
# tomcat的关闭路径
# tomcatStop = "E:\\chinaweal\\apache-tomcat-7.0.47\\bin\\shutdown.bat" 旧的
tomcatStop = "E:\\chinaweal\\apache-tomcat-7.0.85\\bin\\shutdown.bat"
# 要检查的url
# url = "http://gsxt.gzaic.gov.cn/aiccips/GSpublicity/GSpublicityList.html?service=entInfo_2V8NKBAOojn27aIFriSuzocQ0u0FwO6d3DTh4wIf29w=-9Sdep34ycmGGcR7OsMoWBQ=="
url = "http://127.0.0.1:7001/aiccips/GSpublicity/GSpublicityList.html?service=entInfo_zVQhqWScY+dEzyg3Pr4dpDNZqhawMYuxzNp+KWhNNls=-u1AUVlGVTlLhrZKUGWrz1w=="

# 启动tomcat
def startTomcat():
    webbrowser.open("file:///" + tomcatStart)

# 关闭tomcat
def stopTomcat():
    # webbrowser.open("file:///" + tomcatStop) 这种方式有时候并不能很好的关闭
    # 终止tomcat 进程，有多个tomcat部署的时候不能使用该方式
    os.system("taskkill /F /IM java.exe")

 # 检查系统是否还存活 true 还存活， false 已经关闭
def checkWeb():
    i = 0
    for i in range(3):
        try:
            i = i + 1
            result = True
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
            response = requests.get(url, timeout = 10) #请求超时时间为10秒
            # encode = response.encoding #从http header 中猜测的相应内容编码方式
            code = response.status_code #http请求的返回状态，若为200则表示请求成功,返回的状态码是 int类型
            print(str(getDateOne()) + "  检测到状态编码：" + str(code))
            if code == 200:
                result = True
            else:
                result = False
            time.sleep(5) #休眠5秒
        except:
            result = False
    return result

# 获取时间
def getDate():
    today = datetime.date.today()
    return today

def getDateOne():
    i = datetime.datetime.now()
    # print("当前时间 %s" % i)
    return i

def mainApp():
    while True:
        print(str(getDateOne()) + " =========开始检测系统状态=============")
        if checkWeb() == False:
            # print(str(getDateOne()) + "  系统异常，无法打开公示系统，开始修复********************·············")
            print(str(getDateOne()) + "\033[32;0m系统异常，无法打开公示系统，开始修复！\033[0m")
            print("=====开始停止tomcat，等待5秒··====")
            stopTomcat()
            time.sleep(5)  # 休眠5秒来关闭应用,系统应用在服务器上关闭有点慢
            print("=====正在重启tomcat====")
            startTomcat()
        else:
            print(str(getDateOne()) + "  ***系统正常***")

        print(str(getDateOne()) + "  =========结束检测系统状态=============")
        time.sleep(60 * 2)  # 休眠3分钟

mainApp()

# getDateOne()